Popular Searches
Popular Course Categories
Popular Courses

XPath with Text

XPath in Selenium

XPath with Text in Selenium

XPath with Text is a powerful technique in Selenium used to locate web elements based on the visible text present inside an HTML element. It is especially useful when an element does not have a unique ID, name, class, or other stable attribute.

In Selenium automation, the text() function can be combined with XPath to identify elements by their exact or partially matching visible text. This technique is commonly useful for locating buttons, links, labels, headings, menu items, messages, table values, and other text-based elements.

XPath is included among the locator strategies covered in Selenium training, along with CSS selectors and other WebElement location techniques. JustAcademy Selenium Training provides training covering Selenium WebDriver, locators, XPath, CSS selectors, TestNG, automation frameworks, and practical projects. You can also explore the JustAcademy Course Demo Registration page.


1. What is XPath?

XPath stands for XML Path Language. It is a query language used to navigate through elements and attributes in an XML or HTML document.

In Selenium, XPath is commonly used to locate elements when standard locators such as ID, name, class name, or tag name are not sufficient.

Basic XPath Syntax

//tagname[@attribute='value']

Example:

//input[@id='username']

This XPath identifies an input element whose ID is username.


2. What is XPath with Text?

XPath with text means locating an HTML element by checking the text contained inside that element.

The XPath text() function is used to match the text node of an element.

Basic Syntax

//tagname[text()='Text Value']

Example:

//button[text()='Login']

This XPath searches for a button whose text is exactly Login.


3. Why Use Text-Based XPath?

Text-based XPath is useful when an element has no reliable unique attribute but contains identifiable visible text.

  • It can locate buttons using their displayed text.
  • It can locate links using their link text.
  • It can locate labels using visible text.
  • It can locate headings and menu items.
  • It can help identify elements in dynamic web applications.
  • It can be combined with other XPath functions and axes.
  • It can provide a readable locator when the text is stable.


4. Basic text() Function

The text() function checks the text node directly inside an element.

Example HTML

<button>Login</button>

XPath

//button[text()='Login']

This XPath identifies the button containing the exact text Login.


5. Exact Text Matching

Exact text matching is used when the complete text value is known.

//button[text()='Submit']

This matches a button whose text is exactly Submit.

Another example:

//a[text()='Home']

This identifies a link whose visible text is exactly Home.

Another example:

//h1[text()='Welcome to Selenium']

This identifies an h1 element containing the exact text Welcome to Selenium.


6. XPath with Text on Buttons

Buttons frequently contain visible text, making text-based XPath useful for button automation.

HTML

<button>Login</button>

<button>Register</button>

<button>Cancel</button>

XPath Examples

//button[text()='Login']

//button[text()='Register']

//button[text()='Cancel']

Selenium can then use these XPath expressions to click the required button.


7. XPath with Text on Links

Links can also be located using their visible text.

HTML

<a href="/home">Home</a>

<a href="/about">About Us</a>

<a href="/contact">Contact</a>

XPath

//a[text()='Home']

//a[text()='About Us']

//a[text()='Contact']


8. XPath with Text on Labels

Labels can be located using their visible text.

<label>Username</label>

<label>Password</label>

XPath:

//label[text()='Username']

//label[text()='Password']

This technique is especially useful when the label text is stable but the associated input has a dynamic ID.


9. XPath with Text on Headings

Heading text can be used as a reference point for locating related elements.

<h2>Login Details</h2>

XPath:

//h2[text()='Login Details']

Another example:

//h3[text()='Product Details']


10. XPath with Text on Paragraphs

Paragraph elements can also be located using text.

<p>Registration successful</p>

XPath:

//p[text()='Registration successful']

This can be useful for validating success messages in Selenium tests.


11. XPath with Text on Div Elements

Many modern web applications display information inside div elements. Text-based XPath can be used when the div contains identifiable text.

<div>Payment Successful</div>

XPath:

//div[text()='Payment Successful']


12. XPath with Text on Span Elements

<span>Available</span>

XPath:

//span[text()='Available']

This can be used to locate status labels, prices, notifications, badges, and other text elements.


13. Text Matching with Spaces

Whitespace can affect exact text matching. Consider the following HTML:

<button> Login </button>

An exact XPath may not always behave as expected when whitespace is present.

In such cases, normalize-space() can be useful.

//button[normalize-space()='Login']

This normalizes surrounding whitespace before comparing the text.


14. normalize-space() with XPath Text

The normalize-space() function removes leading and trailing whitespace and normalizes sequences of whitespace characters.

Example

<button>   Login   </button>

XPath:

//button[normalize-space()='Login']

This is often more robust than a simple text() comparison when HTML formatting introduces extra spaces.


15. Exact Text vs normalize-space()

MethodExampleUse
Exact text//button[text()='Login']When text formatting is stable
normalize-space()//button[normalize-space()='Login']When unwanted whitespace may exist


16. XPath with contains() and Text

The contains() function can be used when only part of the text is known.

Syntax

//tagname[contains(text(),'partial text')]

Example:

//button[contains(text(),'Login')]

This can match a button whose text contains Login.


17. Exact Text vs contains() Text

XPathPurpose
//button[text()='Login']Matches exact text
//button[contains(text(),'Login')]Matches text containing Login

For example, text()='Login' is intended for an exact match, while contains(text(),'Login') can match values such as Login Now or User Login, depending on the DOM text node.


18. contains() with Long Button Text

Suppose the HTML contains:

<button>Login to Account</button>

XPath:

//button[contains(text(),'Login')]

This is useful when the complete button text is longer or may change slightly.


19. contains() with Link Text

//a[contains(text(),'Learn More')]

This can locate a link whose visible text contains Learn More.

Example:

//a[contains(text(),'Download')]

This can be useful for links such as Download Report or Download PDF.


20. contains() with Heading Text

//h2[contains(text(),'Selenium')]

This can locate an h2 heading containing the word Selenium.


21. contains() with normalize-space()

For text containing additional whitespace, normalize-space() can be combined with contains().

//button[contains(normalize-space(),'Login')]

This expression can be useful when the button text contains additional whitespace.


22. XPath with Text and Attributes

Text conditions can be combined with attributes to make an XPath more specific.

//button[@type='submit' and text()='Login']

This searches for a button whose type is submit and whose text is Login.

Another example:

//a[@class='menu-link' and text()='Home']


23. XPath with Text and Multiple Conditions

The and operator can combine multiple conditions.

//button[@type='button' and contains(text(),'Login')]

The or operator can be used when either condition is acceptable.

//button[text()='Login' or text()='Sign In']

This can locate a button containing either Login or Sign In as its text.


24. XPath with Text and Parent

Text can be combined with the parent axis to locate an element relative to a text-based element.

//label[text()='Username']/parent::div

This first locates the Username label and then moves to its parent div.


25. XPath with Text and Following

Text-based XPath can be combined with the following axis.

//label[text()='Username']/following::input[1]

This identifies the Username label using text and then locates the first input appearing after it.


26. XPath with Text and Preceding

The preceding axis can also be combined with text.

//button[text()='Submit']/preceding::input[1]

This locates an input appearing before the Submit button.


27. XPath with Text and Following-Sibling

If the required element is a sibling of a text-based element, following-sibling can be used.

//label[text()='Email']/following-sibling::input

This searches for an input that is a following sibling of the Email label.


28. XPath with Text and Preceding-Sibling

//input[@type='password']/preceding-sibling::label

This searches for a label that is a preceding sibling of the password input.


29. XPath with Text in Forms

Forms are one of the common situations where text-based XPath is useful.

HTML Example

<label>Username</label>

<input type="text">

<label>Password</label>

<input type="password">

<button>Login</button>

XPath Examples

//label[text()='Username']/following::input[1]

//label[text()='Password']/following::input[1]

//button[text()='Login']


30. XPath with Text in E-Commerce Applications

Product names, categories, prices, and action buttons are often visible as text.

Example HTML

<h3>Laptop</h3>

<span>$800</span>

<button>Add to Cart</button>

XPath Examples

//h3[text()='Laptop']

//span[text()='$800']

//button[text()='Add to Cart']

Text-based XPath can also be combined with relationships.

//h3[text()='Laptop']/following::button[1]


31. XPath with Text in Tables

Table cells often contain meaningful text that can be used as a reference.

Example

<table>

<tr>

<td>John</td>

<td>Completed</td>

</tr>

</table>

XPath:

//td[text()='John']

To find the status:

//td[text()='John']/following-sibling::td

This approach can be useful for validating table data.


32. XPath with Text for Error Messages

Validation messages can often be located using visible text.

<span class="error">Invalid username</span>

XPath:

//span[text()='Invalid username']

With contains:

//span[contains(text(),'Invalid')]


33. XPath with Text for Success Messages

<div class="success">Registration Successful</div>

XPath:

//div[text()='Registration Successful']

Or:

//div[contains(text(),'Successful')]


34. XPath with Text for Menu Items

Navigation menus frequently contain stable visible text.

<nav>

<a>Home</a>

<a>Products</a>

<a>Services</a>

<a>Contact</a>

</nav>

XPath examples:

//a[text()='Home']

//a[text()='Products']

//a[text()='Services']

//a[text()='Contact']


35. XPath with Text for Dropdown Options

Visible option text can be used when working with HTML select elements or custom dropdown components.

//option[text()='India']

For a custom dropdown:

//li[text()='India']

If the option text contains additional words:

//li[contains(text(),'India')]


36. XPath with Text for Checkboxes

Checkboxes themselves may not contain visible text, but their associated labels often do.

<label>

<input type="checkbox">

I agree to the terms

</label>

A text-based XPath can identify the label:

//label[contains(text(),'I agree to the terms')]

Depending on the DOM structure, the input can then be located relative to the label.


37. XPath with Text for Radio Buttons

<label>

<input type="radio" name="gender">

Male

</label>

XPath:

//label[contains(text(),'Male')]

The exact XPath for the radio input depends on the structure of the HTML.


38. XPath with Text and Java Selenium

Selenium Java uses By.xpath() to locate an element using XPath.

WebElement loginButton = driver.findElement(

    By.xpath("//button[text()='Login']")

);

loginButton.click();

This code finds the Login button using its visible text and clicks it.


39. Selenium Example with contains()

WebElement button = driver.findElement(

    By.xpath("//button[contains(text(),'Login')]")

);

button.click();

This is useful when the button contains additional text around the word Login.


40. Selenium Example with normalize-space()

WebElement loginButton = driver.findElement(

    By.xpath("//button[normalize-space()='Login']")

);

loginButton.click();

This is useful when unwanted whitespace exists around the visible text.


41. Complete Selenium Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class XPathTextExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        WebElement loginButton = driver.findElement(

            By.xpath("//button[text()='Login']")

        );

 

        loginButton.click();

 

        driver.quit();

    }

}


42. XPath Text with Explicit Wait

When the text-based element appears after page loading or an asynchronous operation, an explicit wait can be used.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//button[normalize-space()='Login']")

    )

);

 

loginButton.click();

Explicit waits help synchronize Selenium actions with the state of the web application.


43. XPath Text in Dynamic Web Applications

Modern applications may generate dynamic IDs and class names. In such cases, visible text can sometimes provide a stable reference.

Example:

//button[contains(text(),'Submit')]

Instead of relying on a generated attribute such as:

//button[@id='button_849372']

A text-based locator can sometimes remain usable if the displayed text is stable.


44. XPath Text with Multiple Matching Elements

If multiple elements contain the same text, Selenium may find multiple matching nodes. An index or additional condition can be used when appropriate.

//button[text()='Edit'][1]

This selects the first matching Edit button in the result.

Another approach is to narrow the search using an attribute:

//button[@class='edit-btn' and text()='Edit']


45. XPath Text with Index

Indexes can be used when several elements have identical text.

(//button[text()='Edit'])[1]

The parentheses are important when applying the index to the complete XPath result.

Another example:

(//a[text()='View'])[2]

This selects the second matching View link.


46. XPath Text with Parentheses

Parentheses are useful when an index needs to be applied to the complete result set.

(//button[text()='Submit'])[1]

Without parentheses, an index can be interpreted within the location step differently depending on the XPath expression.


47. text() vs .

There is an important difference between using text() and the dot . in XPath.

Using text()

//div[text()='Login']

This checks the direct text node of the div.

Using dot

//div[.='Login']

The dot represents the string value of the current node and can be useful when text is nested inside child elements.


48. text() with Nested Elements

Consider:

<button>

<span>Login</span>

</button>

Depending on the DOM structure, this may make the following expression less suitable:

//button[text()='Login']

An alternative can be:

//button[.='Login']

Or:

//button[span[text()='Login']]

The correct expression should be selected according to the actual DOM structure.


49. XPath Text with Nested Span

Consider the following HTML:

<button>

<span>Add</span>

<span>to Cart</span>

</button>

A direct text-node expression may not be the most suitable approach. You can use:

//button[contains(.,'Add') and contains(.,'Cart')]

This checks the string value of the button and can handle text distributed across nested elements.


50. XPath with Text and Case Sensitivity

XPath text comparisons are generally case-sensitive.

//button[text()='Login']

This is different from:

//button[text()='login']

If the actual text is Login, changing the capitalization can cause the second XPath to fail.

For case-insensitive matching, XPath 1.0 techniques such as translate() can be used.


51. Case-Insensitive Text Matching with translate()

The translate() function can convert uppercase characters to lowercase characters before comparison.

//button[

translate(text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')

='login'

]

This approach can be useful when the capitalization of the visible text is inconsistent.


52. XPath Text with Dynamic Text

Sometimes only part of the text remains stable while the rest changes dynamically.

Example:

<div>Order ID: 123456</div>

Instead of matching the complete dynamic text, use:

//div[contains(text(),'Order ID:')]

This allows the dynamic order number to change while the stable text remains the locator reference.


53. XPath Text for Dynamic Messages

Suppose an application displays:

Payment successful for transaction 87432

A complete-text XPath would be fragile because the transaction number changes.

A better approach can be:

//div[contains(text(),'Payment successful')]

This targets the stable portion of the message.


54. XPath Text in AJAX Applications

AJAX-based applications can update visible messages without refreshing the complete page.

Example:

//div[contains(text(),'Data saved')]

When such elements are dynamically generated, combine the XPath with an explicit wait.

WebElement message = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.xpath("//div[contains(text(),'Data saved')]")

    )

);


55. XPath Text for Validation

Text-based XPath can be used to validate that a particular message or label appears on the page.

WebElement message = driver.findElement(

    By.xpath("//div[text()='Registration Successful']")

);

 

String actualText = message.getText();

 

System.out.println(actualText);

This can be combined with assertions in a testing framework such as TestNG.


56. XPath Text with TestNG Assertion

WebElement message = driver.findElement(

    By.xpath("//div[normalize-space()='Registration Successful']")

);

 

Assert.assertEquals(

    message.getText(),

    "Registration Successful"

);

This verifies that the expected message is displayed.


57. Real-World Login Example

Suppose a login page contains:

<label>Username</label>

<input type="text">

<label>Password</label>

<input type="password">

<button>Login</button>

Locate the Login button:

//button[text()='Login']

Locate the username input using the Username label:

//label[text()='Username']/following::input[1]

Locate the password input:

//label[text()='Password']/following::input[1]


58. Real-World E-Commerce Example

Suppose an e-commerce product card contains:

<div class="product">

<h3>Laptop</h3>

<span>₹50000</span>

<button>Add to Cart</button>

</div>

Locate the product:

//h3[text()='Laptop']

Locate the price:

//h3[text()='Laptop']/following-sibling::span

Locate the Add to Cart button:

//h3[text()='Laptop']/following-sibling::button


59. Real-World Table Example

Consider a table containing customer information:

<tr>

<td>John</td>

<td>[email protected]</td>

<td>Active</td>

</tr>

Locate the row using the customer name:

//tr[td[text()='John']]

Locate the email cell:

//tr[td[text()='John']]/td[text()='[email protected]']

Locate the status:

//tr[td[text()='John']]/td[text()='Active']


60. Common Mistakes in XPath with Text

  • Using incorrect capitalization.
  • Using exact text when the text contains extra whitespace.
  • Using text() when the visible text is inside nested elements.
  • Using contains() too broadly.
  • Ignoring duplicate text values.
  • Depending on frequently changing dynamic text.
  • Using indexes without understanding the DOM structure.
  • Not testing the XPath in browser DevTools.
  • Ignoring dynamic loading and synchronization.
  • Creating unnecessarily complex XPath expressions.


61. Best Practices for XPath with Text

  • Use exact text when the text is stable and unique.
  • Use normalize-space() when unwanted whitespace is possible.
  • Use contains() when only part of the text is stable.
  • Combine text with attributes when duplicate text exists.
  • Use relationships such as parent, following, and preceding when necessary.
  • Use indexes only when there is no better unique locator.
  • Check whether the text is directly inside the element or nested inside child elements.
  • Prefer stable text over dynamic text.
  • Test XPath expressions using Chrome DevTools.
  • Use explicit waits for dynamically rendered elements.
  • Keep XPath expressions readable and maintainable.


62. How to Test XPath with Text in Chrome DevTools

  1. Open the application in Google Chrome.
  2. Right-click the required element.
  3. Select Inspect.
  4. Open the Console tab.
  5. Use the $x() function.
  6. Enter the XPath expression.

Example:

$x("//button[text()='Login']")

Contains example:

$x("//button[contains(text(),'Login')]")

Normalize-space example:

$x("//button[normalize-space()='Login']")


63. XPath Text Cheat Sheet

RequirementXPath
Exact button text//button[text()='Login']
Exact link text//a[text()='Home']
Exact heading text//h1[text()='Welcome']
Partial button text//button[contains(text(),'Login')]
Text with whitespace//button[normalize-space()='Login']
Text and attribute//button[@type='submit' and text()='Login']
Text with parent//label[text()='Username']/parent::div
Text with following//label[text()='Username']/following::input[1]
Text with preceding//button[text()='Submit']/preceding::input[1]
Text with following-sibling//label[text()='Email']/following-sibling::input
Text with preceding-sibling//input[@type='password']/preceding-sibling::label
First matching text element(//button[text()='Edit'])[1]
Dynamic text//div[contains(text(),'Order ID:')]


64. Interview Questions on XPath with Text

  1. What is the text() function in XPath?
  2. How do you locate a button using its text?
  3. What is the difference between text() and contains(text())?
  4. How do you handle extra whitespace in XPath text?
  5. What is normalize-space()?
  6. How do you locate a link using visible text?
  7. How do you locate an element when only partial text is known?
  8. What is the difference between text() and dot in XPath?
  9. How do you handle nested text elements?
  10. How do you create a case-insensitive text XPath?
  11. How can text XPath be combined with attributes?
  12. How can text XPath be combined with following?
  13. How can text XPath be combined with preceding?
  14. How do you handle duplicate elements having the same text?
  15. How do you test text-based XPath in Chrome DevTools?
  16. How do you use text XPath with Selenium Java?
  17. When should you use contains() instead of exact text matching?
  18. How do you locate dynamic messages using XPath text?
  19. How do you use text XPath with explicit waits?
  20. What are common mistakes when using XPath with text?


65. Interview Answers: XPath with Text

Q1. What is text() in XPath?

The text() function is used to match the text node of an HTML element.

Q2. How do you locate a Login button using text?

//button[text()='Login']

Q3. How do you locate an element containing partial text?

//button[contains(text(),'Login')]

Q4. How do you handle extra whitespace?

//button[normalize-space()='Login']

Q5. How do you locate an input after a label?

//label[text()='Username']/following::input[1]

Q6. What if text is inside a child element?

Depending on the DOM structure, the dot operator or a child-element XPath can be used.

//button[.='Login']

Or:

//button[span[text()='Login']]


66. Practical XPath Text Checklist

  • Inspect the element in Chrome DevTools.
  • Identify the exact visible text.
  • Check whether the text is directly inside the element.
  • Try exact text matching with text().
  • Use normalize-space() if whitespace is present.
  • Use contains() when only partial text is stable.
  • Check whether multiple elements have the same text.
  • Add attributes when necessary.
  • Use XPath axes for related elements.
  • Test the XPath using $x().
  • Use explicit waits for dynamic elements.
  • Use the final XPath in Selenium with By.xpath().


67. Conclusion

XPath with Text is an important Selenium locator technique for identifying elements based on visible text. The text() function can be used for exact text matching, while contains() can be used when only a portion of the text is stable. The normalize-space() function is useful when extra whitespace affects text matching.

Text-based XPath can also be combined with attributes, parent-child relationships, following, preceding, following-sibling, preceding-sibling, indexes, and other XPath functions. Understanding these combinations helps testers create locators for forms, buttons, links, tables, product pages, messages, menus, and dynamic web applications.

For structured Selenium automation learning covering Selenium WebDriver, locators, XPath, CSS selectors, TestNG, frameworks, and practical automation projects, visit JustAcademy Selenium Training.

For course demonstration registration, visit JustAcademy Course Demo Registration.

whatsapp